package com.ffggffgfv.backend.controller;

import com.ffggffgfv.backend.dto.ShippingAddressDTO;
import com.ffggffgfv.backend.entity.ShippingAddress;
import com.ffggffgfv.backend.service.ShippingAddressService;
import com.ffggffgfv.backend.util.JWTUtil;
import com.ffggffgfv.backend.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 收货地址控制器
 */
@RestController
@RequestMapping("/api/address")
public class ShippingAddressController {

    @Autowired
    private ShippingAddressService shippingAddressService;

    @Autowired
    private JWTUtil jwtUtil;

    /**
     * 获取用户的收货地址列表
     *
     * @param token JWT令牌
     * @return 地址列表
     */
    @GetMapping("/list")
    public Result getAddressList(@RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        List<ShippingAddress> addressList = shippingAddressService.getList(userId);
        return Result.success(addressList, "获取地址列表成功");
    }

    /**
     * 获取收货地址详情
     *
     * @param id    地址ID
     * @param token JWT令牌
     * @return 地址详情
     */
    @GetMapping("/{id}")
    public Result getAddress(@PathVariable Long id, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        ShippingAddress address = shippingAddressService.getById(userId, id);
        if (address == null) {
            return Result.validateFailed("地址不存在或无权访问");
        }

        return Result.success(address, "获取地址详情成功");
    }

    /**
     * 获取默认收货地址
     *
     * @param token JWT令牌
     * @return 默认地址
     */
    @GetMapping("/default")
    public Result getDefaultAddress(@RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        ShippingAddress address = shippingAddressService.getDefaultAddress(userId);
        if (address == null) {
            return Result.success(null, "用户没有设置默认地址");
        }

        return Result.success(address, "获取默认地址成功");
    }

    /**
     * 添加收货地址
     *
     * @param addressDTO 收货地址信息
     * @param token      JWT令牌
     * @return 添加结果
     */
    @PostMapping("/add")
    public Result addAddress(@RequestBody ShippingAddressDTO addressDTO, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        // 参数验证
        if (addressDTO.getReceiverName() == null || addressDTO.getReceiverName().trim().isEmpty()) {
            return Result.validateFailed("收货人姓名不能为空");
        }
        if (addressDTO.getReceiverPhone() == null || addressDTO.getReceiverPhone().trim().isEmpty()) {
            return Result.validateFailed("收货人电话不能为空");
        }
        if (addressDTO.getProvince() == null || addressDTO.getProvince().trim().isEmpty() ||
                addressDTO.getCity() == null || addressDTO.getCity().trim().isEmpty() ||
                addressDTO.getDetailAddress() == null || addressDTO.getDetailAddress().trim().isEmpty()) {
            return Result.validateFailed("收货地址不完整");
        }

        try {
            ShippingAddress address = shippingAddressService.add(userId, addressDTO);
            return Result.success(address, "添加地址成功");
        } catch (Exception e) {
            return Result.validateFailed("添加地址失败: " + e.getMessage());
        }
    }

    /**
     * 更新收货地址
     *
     * @param id         地址ID
     * @param addressDTO 收货地址信息
     * @param token      JWT令牌
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public Result updateAddress(
            @PathVariable Long id,
            @RequestBody ShippingAddressDTO addressDTO,
            @RequestHeader(value = "Authorization") String token) {

        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        ShippingAddress updatedAddress = shippingAddressService.update(userId, id, addressDTO);
        if (updatedAddress == null) {
            return Result.validateFailed("更新地址失败，地址可能不存在或无权操作");
        }

        return Result.success(updatedAddress, "更新地址成功");
    }

    /**
     * 删除收货地址
     *
     * @param id    地址ID
     * @param token JWT令牌
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result deleteAddress(@PathVariable Long id, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        boolean result = shippingAddressService.delete(userId, id);
        if (result) {
            return Result.success(null, "删除地址成功");
        } else {
            return Result.validateFailed("删除地址失败，地址可能不存在或无权操作");
        }
    }

    /**
     * 设置默认收货地址
     *
     * @param id    地址ID
     * @param token JWT令牌
     * @return 设置结果
     */
    @PostMapping("/set-default/{id}")
    public Result setDefaultAddress(@PathVariable Long id, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        boolean result = shippingAddressService.setDefault(userId, id);
        if (result) {
            return Result.success(null, "设置默认地址成功");
        } else {
            return Result.validateFailed("设置默认地址失败，地址可能不存在或无权操作");
        }
    }

    /**
     * 从令牌中提取用户ID
     *
     * @param token JWT令牌
     * @return 用户ID
     */
    private Long getUserIdFromToken(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                return jwtUtil.getUserIdFromToken(token);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}
